// pages/userInfo/userInfo.js
const API = {
  USER: 'http://116.205.102.248:8080/user/UserView/'
};

Page({
  data: {
    // 用户数据
    user_image: null,
    user_nick: '',
    user_sex: 0,

    // 系统数据
    originalData: {},      // 初始数据
    modifiedData: {},      // 修改后的数据
    lastSavedData: {},     // 上一次成功提交后的数据
    sexMap: { 0: '未知', 1: '男', 2: '女' },
    token: ''
  },

  ToHome() {
    wx.navigateBack({ delta: 1 });
  },

  onLoad() {
    this.initData();
    this.fetchUserData(); // 获取最新数据
  },

  // 初始化数据
  async initData() {
    try {
      const token = wx.getStorageSync('token');
      if (!token) throw new Error('登录状态已过期');
      this.setData({ token }, () => this.fetchUserData());
    } catch (error) {
      this.showError('请重新登录', () => wx.reLaunch({ url: '/pages/login/login' }));
    }
  },

  // 获取用户数据
  async fetchUserData() {
    wx.showLoading({ title: '加载中...', mask: true });
    
    try {
      const { data } = await this.request({
        url: API.USER,
        method: 'GET'
      });

      console.log('获取用户数据成功，响应数据:', data); // 打印响应数据

      this.setData({
        user_image: data.user_image || '../../pages/imgs/初始头像.png',
        user_nick: data.user_nick,
        user_sex: data.user_sex || 0,
        originalData: this.deepClone(data), // 初始数据
        lastSavedData: this.deepClone(data) // 上一次提交后的数据
      });
      console.log('更新后的页面数据:', this.data); // 打印更新后的页面数据
    } catch (error) {
      console.error('获取用户数据失败:', error); // 打印错误信息
      this.showError(error.message);
    } finally {
      wx.hideLoading();
    }
  },

  // 修改头像
  async handleAvatarChange() {
    try {
      const { tempFiles } = await wx.chooseMedia({
        count: 1,
        sourceType: ['album', 'camera'],
        mediaType: ['image']
      });

      this.setData({
        user_image: tempFiles[0].tempFilePath,
        modifiedData: { 
          ...this.data.modifiedData,
          user_image: tempFiles[0].tempFilePath
        }
      });
    } catch (error) {
      console.log('取消选择');
    }
  },

  // 修改昵称
  handleNickChange() {
    wx.showModal({
      title: '修改昵称',
      editable: true,
      success: res => {
        if (res.confirm && res.content) {
          this.setData({
            user_nick: res.content,
            modifiedData: {
              ...this.data.modifiedData,
              user_nick: res.content
            }
          });
          console.log('修改后的昵称:', res.content); // 打印新昵称
        }
      }
    });
  },

  // 修改性别
  handleSexChange() {
    wx.showActionSheet({
      itemList: ['男', '女'],
      success: res => {
        const newSex = res.tapIndex + 1;
        this.setData({
          user_sex: newSex,
          modifiedData: {
            ...this.data.modifiedData,
            user_sex: newSex
          }
        });
      }
    });
  },

  // 提交修改
  async handleSubmit() {
    const modifiedData = { ...this.data.modifiedData };
    if (Object.keys(modifiedData).length === 0) {
      return this.showError('请先修改信息');
    }

    console.log('正在提交修改，修改的字段:', modifiedData); // 打印修改的字段

    wx.showLoading({ title: '提交中...', mask: true });

    try {
      const fields = Object.keys(modifiedData);
      for (const field of fields) {
        const value = modifiedData[field];
        await this.updateField(field, value);
      }

      // 提交成功后更新 lastSavedData
      this.setData({
        lastSavedData: { 
          ...this.data.lastSavedData,
          ...modifiedData 
        },
        modifiedData: {}
      });
      console.log('所有字段提交成功'); // 打印提交成功信息
      wx.showToast({ title: '修改成功' });
    } catch (error) {
      console.error('提交失败:', error); // 打印提交失败信息
      this.showError('提交失败: ' + error.message);
    } finally {
      wx.hideLoading();
    }
  },

  // 取消修改
  handleCancel() {
    this.setData({
      user_image: this.data.lastSavedData.user_image || '../../pages/imgs/初始头像.png',
      user_nick: this.data.lastSavedData.user_nick||'',
      user_sex: this.data.lastSavedData.user_sex || 0,
      modifiedData: {}
    });
    wx.showToast({ title: '已恢复上次修改', icon: 'success' });
  },

  // 更新单个字段
  async updateField(field, value) {
    const boundary = `----WebKitFormBoundary${Math.random().toString(16)}`;
    const { header, body } = await this.buildRequestContent(field, value, boundary);

    console.log(`正在更新字段: ${field}，值: ${value}`); // 打印更新字段信息

    return new Promise((resolve, reject) => {
      wx.request({
        url: API.USER,
        method: 'PUT',
        header: {
          'Authorization': this.data.token,
          ...header
        },
        data: body,
        success: (res) => {
          console.log(`字段 ${field} 更新成功，响应数据:`, res.data); // 打印成功响应
          if (res.statusCode === 200) {
            resolve(res.data[field]);
          } else {
            reject(new Error(res.data.message || '接口返回错误'));
          }
        },
        fail: (err) => {
          console.error(`字段 ${field} 更新失败:`, err); // 打印失败信息
          reject(err);
        }
      });
    });
  },

  // 构建请求内容
  async buildRequestContent(field, value, boundary) {
    const lineBreak = '\r\n';
    let body = '';

    if (field === 'user_image') {
      const fileData = await this.readFile(value);
      body += `--${boundary}${lineBreak}`;
      body += `Content-Disposition: form-data; name="${field}"; filename="avatar_${Date.now()}.jpg"${lineBreak}`;
      body += `Content-Type: image/jpeg${lineBreak}${lineBreak}`;
      body += fileData;
    } else {
      body += `--${boundary}${lineBreak}`;
      body += `Content-Disposition: form-data; name="${field}"${lineBreak}${lineBreak}`;
      body += value.toString();
    }

    body += `${lineBreak}--${boundary}--${lineBreak}`;

    return {
      header: {
        'Content-Type': `multipart/form-data; boundary=${boundary}`
      },
      body: body
    };
  },

  // 读取文件内容
  readFile(filePath) {
    return new Promise((resolve, reject) => {
      wx.getFileSystemManager().readFile({
        filePath,
        encoding: 'binary',
        success: (res) => resolve(res.data),
        fail: () => reject(new Error('文件读取失败'))
      });
    });
  },

  // 通用请求方法
  request(options) {
    console.log('发起请求:', {
      url: options.url,
      method: options.method,
      data: options.data
    }); // 打印请求信息

    return new Promise((resolve, reject) => {
      wx.request({
        ...options,
        header: {
          'Authorization': this.data.token,
          ...options.header
        },
        success: (res) => {
          console.log('请求成功，响应状态码:', res.statusCode, '响应数据:', res.data); // 打印响应信息
          if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve(res.data);
          } else {
            reject(new Error(res.data.message || `请求失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          console.error('请求失败:', err); // 打印失败信息
          reject(err);
        }
      });
    });
  },

  // 深度克隆
  deepClone(obj) {
    return JSON.parse(JSON.stringify(obj));
  },

  // 错误处理
  showError(msg, callback) {
    wx.showModal({
      title: '提示',
      content: msg,
      showCancel: false,
      complete: () => callback && callback()
    });
  }
});